<?php


namespace app\admin\controller\auth;

use app\admin\controller\AController;
use app\admin\service\auth\AdminRuleService;
use app\admin\service\CurdService;
use app\admin\service\RequestService;
use app\admin\validate\auth\AdminRuleValidate;
use app\model\auth\AdminRule;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\response\Json;

class AdminRuleController extends AController {

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function index(RequestService $requestService, AdminRuleService $adminRuleService): Json
    {
        $list = $requestService->read(new AdminRule(), isPage: false, order: "sort desc");
        $tree = $adminRuleService->childrenTree($list);

        return jsonSuccess([
            'items' => $tree
        ]);

    }


    public function add(Request $request, RequestService $requestService): Json
    {

        if ($request->isPost()){
            $data = $request->except(['create_time', 'update_time', 'toolbar'], 'post');
            // 验证表单数据
            try {
                validate(AdminRuleValidate::class)->check($data);
            } catch (\Exception $e) {
                // 验证失败 输出错误信息
                return jsonError($e->getMessage());
            }

            $curdSer = new CurdService(new AdminRule());
            $info = $curdSer->create($data);

            // 添加增删改查等操作
            $toolbar = $request->param('toolbar', []);
            $this->editChildrenBar($info, $toolbar);
        }
        return jsonSuccess();
    }

    // 重写编辑方法
    public function edit(Request $request): Json
    {

        $id = $request->param('id');
        if(!$id){
            return jsonError('无此记录');
        }

        if($request->isPost()){

            $data = $request->except(['create_time', 'update_time', 'toolbar'], 'post');
            // 验证表单数据
            try {
                validate(AdminRuleValidate::class)->check($data);
            } catch (\Exception $e) {
                // 验证失败 输出错误信息
                return jsonError($e->getMessage());
            }

            $curdSer = new CurdService(new AdminRule());
            $info = $curdSer->update($data, ['id' => $data['id']]);

            // 添加增删改查等操作
            $toolbar = $request->param('toolbar', []);
            $this->editChildrenBar($info, $toolbar);

            return jsonSuccess([
                'info' => $info
            ]);

        }else{

            $info = AdminRule::where('id', $id)->find();

            if (!$info){
                return jsonError(NOT_FOUND);
            }
            return jsonSuccess([
                'info' => $info
            ]);
        }
    }


    public function del(Request $request, AdminRuleService $adminRuleService){
        if ($request->isPost()){
            $ids = $request->param('ids');
            $rules = AdminRule::field(['id','pid'])->select();
            // 将所有的子孙级存入数组中
            $arr = array();
            foreach ($ids as $id){
                $ia = $adminRuleService->childrenIds($rules, $id);
                $arr = $arr + $ia;
            }
            $ids = array_merge($ids,$arr);
            // 删除
            $curdSer = new CurdService(new AdminRule());
            $curdSer->destroy($ids);

            return jsonSuccess();
        }
    }

    /**
     * 权限规则选项
     * @param AdminRuleService $adminRuleService
     * @return Json
     */
    public function options(AdminRuleService $adminRuleService): Json
    {
        return jsonSuccess([
            'options' => $adminRuleService->options()
        ]);

    }

    private function editChildrenBar(AdminRule $info, $toolbar){
        // 添加增删改查等操作
        $model = $info->name;
        $toolbarData = [
            'pid' =>  $info->id,
            'type' => 1,
            'is_menu' => 0,
            'status' => 1,
            'sort' => '1000',
            'rule_type' => 3
        ];
        foreach($toolbar as $v){
            switch ($v){
                case 'index':
                    $toolbarData['title'] = '列表';
                    $toolbarData['name'] = $model.'/'.$v;
                    break;
                case 'add':
                    $toolbarData['title'] = '添加';
                    $toolbarData['name'] = $model.'/'.$v;
                    break;
                case 'edit':
                    $toolbarData['title'] = '编辑';
                    $toolbarData['name'] = $model.'/'.$v;
                    break;
                case 'del':
                    $toolbarData['title'] = '删除';
                    $toolbarData['name'] = $model.'/'.$v;
                    break;

            }
            AdminRule::create($toolbarData);
        }
    }

}
